import swal from 'sweetalert2';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { LazyLoadEvent } from 'primeng/components/common/api';
import { Http } from '@angular/http';
import { TranslateService } from '@ngx-translate/core';

import { User } from '../../../core/auth/user.service';
import { CommonComponent } from '../../../core/common/common.component';
import { CommonService } from '../../../core/common/common.service';
import { ConfigService } from '../../../core/common/config.service';
import { TableDictService } from '../../../core/common/table-dict.service';
import { SelectComponent } from '../../../shared/component/ng2-select/select';
import { SelectItem } from '../../../shared/component/ng2-select/select-item';
import { ChannelService } from '../service/channel.service';
const styles = `

`;
@Component({
  selector: 'ncloud-channel-add',
  templateUrl: './addChannel.html',
  styles: [styles]
})
export class AddChannel extends CommonComponent implements OnInit {
  public customers: Array<any>;
  public totalRecords: number;
  public nodeInfos: Array<any> = [];
  @ViewChild('province') province: SelectComponent;
  @ViewChild('city') city: SelectComponent;
  private backURL: string;
  public provinces: Array<any> = [];
  public select: any = {};
  private operate: string;
  constructor(private common: CommonService, public user: User, private channelService: ChannelService,
    private route: ActivatedRoute, private router: Router, private tableDict: TableDictService, private http: Http,
    private config: ConfigService, private translate: TranslateService) {
    super();
    if (!this.data) {
      this.data = {};
      this.data.chnlType = '1';
      this.data.parentId = '1';
    }
  }
  writeValue(value) {
    super.writeValue(value);
  }
  ngOnInit() {
    super.ngOnInit();
    this.initProvince();
    this.initParameters();
  }
  private initParameters(): void {
    this.route.params.switchMap((params: Params) => {
      const result: any = [];
      if (params['backURL']) {
        this.backURL = params['backURL'];
      }
      if (params['data']) {
        this.data = JSON.parse(params['data']);
      }
      if (params['operate']) {
        this.operate = params['operate'];
      }
      return result;
    }
    ).subscribe((c: any) => { });
  }
  private initProvince(): void {
    this.tableDict.getProvince().subscribe((data: any) => {
      this.provinces = data;
    });
  }
  public provinceSelected($event: any): void {
    this.tableDict.getCity(this.data.province).subscribe((data: any) => {
      this.city.items = data;
      let exists = false;
      const active: any = this.city.active && this.city.active.length > 0 ? this.city.active[0] : {};
      this.city.itemObjects.forEach((i: SelectItem) => {
        if (i.id === active.id) {
          exists = true;
        }
      });
      if (!exists && this.city.itemObjects.length > 0) {
        this.city.active = [];
      }
    });
  }
  public citySelected($event: any): void {
  }
  loadLazy(event: LazyLoadEvent) {
    setTimeout(() => {
      const pageNum = event.first / event.rows + 1;
      const pageSize = event.rows;
      this.channelService.getChannels(pageNum, pageSize).map((res: Response) => {
        return res.json();
      }).subscribe((channels: any) => {
        this.customers = channels;
      });
    }, 200);
  }
  private check(): boolean {
    if (this.valForm.valid) {
      return true;
    } else {
      this.translate.get(['channel.add.invalid', 'channel.add.warning']).subscribe((res: string) => {
        swal(res['channel.add.warning'], res['channel.add.invalid'], 'warning').catch(swal.noop);
      });
    }
    return false;
  }
  quato(): void {
    this.submit(true);
  }
  submit(isQuato?: boolean): void {
    if (this.check()) {
      let url;
      if (this.operate === '0') {
        url = this.config.get('url') + '?service=ChnlService&method=insertChnl';
      } else {
        url = this.config.get('url') + '?service=ChnlService&method=updateChnl';
      }
      this.http.post(url, this.data).map((resp: any) => {
        return resp.json();
      }).subscribe((json: any) => {
        if (json.code === '0000') {
          const array = ['channel.add.submit.success.title', 'channel.add.submit.success.confirm'];
          if (isQuato) {
            this.router.navigate(['/channel/quato', {
              'backURL': this.common.getCurrentURL(this.route)
            }], { relativeTo: this.route.parent, skipLocationChange: true });
          } else {
            this.translate.get(array).subscribe((res: string) => {
              swal({
                title: res['channel.add.submit.success.title'],
                type: 'success',
                timer: 3000,
                confirmButtonColor: '#3085d6',
                confirmButtonText: res['channel.add.submit.success.confirm'],
                confirmButtonClass: 'btn btn-success',
                buttonsStyling: false
              }).then((e: any) => {
                this.back();
              }, (dismiss: any) => {
                this.back();
              });
            });
          }
        } else {
          this.translate.get('channel.add.submit.failed.warning').subscribe((res: string) => {
            swal(res, json.message, 'warning');
          });
        }
      });
    }
  }
  cancel(): void {
    const array = ['channel.add.cancel.title', 'channel.add.cancel.text', 'channel.add.cancel.confirm', 'channel.add.cancel.cancel'];
    this.translate.get(array).subscribe((res: string) => {
      swal({
        title: res['channel.add.cancel.title'],
        text: res['channel.add.cancel.text'],
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: res['channel.add.cancel.confirm'],
        cancelButtonText: res['channel.add.cancel.cancel'],
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger'
      }).then((e: any) => {
        this.back();
      }, (dismiss: any) => {
        // dismiss can be 'cancel', 'overlay',
        // 'close', and 'timer'
      });
    });
  }
  private back(): void {
    this.router.navigate([this.backURL]);
  }
}
